package com.example.demo.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;

import com.alibaba.fastjson2.JSONObject;

import androidx.appcompat.app.AppCompatActivity;

import com.example.demo.databinding.ActivityDayInHistoryBinding;

import java.util.Objects;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class DayInHistoryActivity extends AppCompatActivity {
    private static final String TAG = "DayInHistoryActivity";

    private ActivityDayInHistoryBinding binding;

    private String url = "https://api.jisuapi.com/todayhistory/query?appkey=d65c8d176fe7c273&month=@month@&day=@day@";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityDayInHistoryBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        loadInfo();
        setJump();
    }

    private void setJump(){
        binding.jumpToAstro.setOnClickListener(view -> {
            startActivity(new Intent(this, AstroActivity.class));
        });
        binding.jumpToHis.setOnClickListener(view -> {
            startActivity(new Intent(this, DayInHistoryActivity.class));
        });
        binding.jumpToGold.setOnClickListener(view -> {
            startActivity(new Intent(this, GoldActivity.class));
        });
        binding.jumpToNews.setOnClickListener(view -> {
            startActivity(new Intent(this, NewsListActivity.class));
        });
        binding.jumpToPhone.setOnClickListener(view -> {
            startActivity(new Intent(this, PhoneActivity.class));
        });
    }

    private void loadInfo() {
        new Thread(() -> {
            try{
                OkHttpClient client = new OkHttpClient();
                String url = this.url.replace("@month@", "")
                        .replace("@day@", "");
                Request request = new Request.Builder() .url(url) .build();
                Response response = client.newCall(request).execute();
                String body = response.body().string();


                DayInHistoryActivity.this.runOnUiThread(() -> {
                    Log.i(TAG, body);

                    JSONObject mapObj = JSONObject.parseObject(body);
                    JSONObject info =  mapObj.getJSONArray("result").getJSONObject(0);
                    String time = info.getString("year")+"-"+info.getString("month")+"-"+info.getString("day");
                    binding.dayInHistoryTitle.setText(info.getString("title"));
                    binding.dayInHistoryTime.setText(time);
                    binding.dayInHistorContent.setText(Html.fromHtml(info.getString("content"), Html.FROM_HTML_MODE_COMPACT));
                });


            }catch (Exception e){
                Log.i(TAG, Objects.requireNonNull(e.getMessage()));
            }
        }).start();

    }

}